package com.sanjiahantang.youjiaclient.module.decorate.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;

import com.amap.api.maps2d.model.Text;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.dialog.CommonDialog;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseBean;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.module.city.models.ICityModel;
import com.sanjiahantang.youjiaclient.module.city.models.impl.CityModel;
import com.sanjiahantang.youjiaclient.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiaclient.module.common.beans.FileBean;
import com.sanjiahantang.youjiaclient.module.common.beans.StringBean;
import com.sanjiahantang.youjiaclient.module.common.models.IFileModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.FileModel;
import com.sanjiahantang.youjiaclient.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiaclient.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiaclient.module.decorate.beans.CheckPayBean;
import com.sanjiahantang.youjiaclient.module.decorate.beans.DecorateDicBean;
import com.sanjiahantang.youjiaclient.module.decorate.beans.DecorateManageBean;
import com.sanjiahantang.youjiaclient.module.decorate.models.IDecorateModel;
import com.sanjiahantang.youjiaclient.module.decorate.models.impl.DecorateModel;
import com.sanjiahantang.youjiaclient.module.decorate.views.DecorateManageView;
import com.sanjiahantang.youjiaclient.module.decorate.views.impl.DecorateDetailFragment;
import com.sanjiahantang.youjiaclient.module.me.order.beans.ServiceListBean;
import com.sanjiahantang.youjiaclient.module.me.order.views.impl.ServiceOrderActivity;
import com.sanjiahantang.youjiaclient.module.store.views.impl.NearbyStoreActivity;
import com.sanjiahantang.youjiaclient.utils.SPUtils;

import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zy on 2017/9/14.
 */

public class DecorateManagePresenter extends BaseMvpPresenter<DecorateManageView> {

    private IDecorateModel decorateModel;
    private FragmentManager fragmentManager;
    private FragmentTransaction ft;
    private CommonNavigatorAdapter tabAdapter;
    private List<DecorateManageBean.Data> tabList;
    private DecorateManageView.BindPageListener bindPageListener;
    private QuickAdapter<DecorateManageBean.Step> flowAdapter;
    private DecorateManageView.OnLoadListener onLoadListener;
    private ICityModel cityModel;
    private DecorateManageView.BindTabListener bindTabListener;
    private IFileModel fileModel;

    public DecorateManagePresenter() {
        decorateModel = new DecorateModel();
        tabList = new ArrayList<>();
        cityModel = new CityModel();
        fileModel = new FileModel();
    }

    public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    public void loadTab(Context context, final int currentPiId, final DecorateManageView.BindTabListener bindTabListener) {
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put("customerPhone", SPUtils.get(context, SPConfig.PHONE, "").toString());
        params.put("piId", "0");
        decorateModel.loadTab(context, params, new CallBack<DecorateManageBean>() {

            @Override
            public void onSuccess(DecorateManageBean response, Context context, Object tag) {
                ConfigValue.isLocked = false;
                if (mView == null) return;
                hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC && response.getData() != null) {
                    tabList.clear();
                    tabList.addAll(response.getData());
                    tabAdapter.notifyDataSetChanged();
                    if (response.getData().size() > 0) {
                        boolean hasTab = false;
                        int index = 0;
                        for (DecorateManageBean.Data item : response.getData()) {
                            if (item.getPiId() == currentPiId) {
                                DecorateManagePresenter.this.bindTabListener.switchPages(index);
                                DecorateManagePresenter.this.bindTabListener.changeFragment(item);
                                hasTab = true;
                                break;
                            }
                            index++;
                        }
                        if (!hasTab) {
                            DecorateManagePresenter.this.bindTabListener.changeFragment(tabList.get(0));
                        }

                    } else {
                        Utils.showToast(context, "您暂无装修管理项目");
                        DecorateManagePresenter.this.bindTabListener.changeFragment(null);
                    }

                } else {
                    Utils.showToast(context, "获取装修管理信息失败");
                }

            }

            @Override
            public void onFailure(String message) {
                ConfigValue.isLocked = false;
                hideProgress();
            }
        });
        if (bindTabListener != null) this.bindTabListener = bindTabListener;
        tabAdapter = new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return tabList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
                View contentView = LayoutInflater.from(context).inflate(R.layout.item_radio_line, null);
                commonPagerTitleView.setContentView(contentView);
                final RadioButton btn = (RadioButton) contentView.findViewById(R.id.rbItem);
                btn.setText(tabList.get(index).getEngineName() == null ? ("工程 " + (index + 1)) : tabList.get(index).getEngineName());

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int i, int i1) {
                        btn.setChecked(true);
                    }

                    @Override
                    public void onDeselected(int i, int i1) {
                        btn.setChecked(false);
                    }

                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {

                    }

                    @Override
                    public void onEnter(int i, int i1, float v, boolean b) {

                    }
                });
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DecorateManagePresenter.this.bindTabListener.switchPages(index);
                        DecorateManagePresenter.this.bindTabListener.changeFragment(tabList.get(index));
                    }
                });
                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DecorateManagePresenter.this.bindTabListener.switchPages(index);
                        DecorateManagePresenter.this.bindTabListener.changeFragment(tabList.get(index));
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        };
        this.bindTabListener.bindAdapter(tabAdapter);
    }


    /**
     * 注册后填写需求单页初始化
     *
     * @param context
     */
    public void loadIndexDic(Context context) {
        Map<String, String> param = new HashMap<>();
        if (ConfigValue.DATA_KEY != null) {
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        }
        String phone = SPUtils.get(context, SPConfig.PHONE, "").toString();
        if (!TextUtils.isEmpty(phone)) {
            param.put(KEY_PHONE, phone);
        }
        decorateModel.loadIndexDic(context, param, new LoadIndexDicCallBack());
    }

    public void setOnLoadListener(DecorateManageView.OnLoadListener onLoadListener) {
        this.onLoadListener = onLoadListener;
    }

    public void loadCityList(Context context, BaseView.OnLoadListener listener) {
        cityModel.getAllArea(context, listener);
    }

    public void saveUserRequireInfoIntention(
            final Context context,
            String name,
            int isMan,
            ConditionBean.SelectorData jobData,
            String city,
            String address,
            int hasBaby,
            int hasOld,
            ConditionBean.SelectorData doorData,
            ConditionBean.SelectorData styleData,
            String area,
            ConditionBean.SelectorData priceData,
            String preTime
    ) {
        Map<String, Object> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        param.put(DecorateManageView.KEY_DECORATE_NAME, name);
        param.put(DecorateManageView.KEY_DECORATE_GENDER, isMan);
        param.put(DecorateManageView.KEY_DECORATE_JOB_VALUE, jobData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_JOB_NAME, jobData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_CITY, city);
        param.put(DecorateManageView.KEY_DECORATE_ADDRESS, address);
        param.put(DecorateManageView.KEY_DECORATE_BABY, hasBaby);
        param.put(DecorateManageView.KEY_DECORATE_OLD, hasOld);
        param.put(DecorateManageView.KEY_DECORATE_DOOR_VALUE, doorData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_DOOR_NAME, doorData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_VALUE, styleData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_NAME, styleData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_AREA, area);
        param.put(DecorateManageView.KEY_DECORATE_PRICE_VALUE, priceData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_PRICE_NAME, priceData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_PRE_TIME, preTime);
        decorateModel.saveUserRequireInfoIntention(context, param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                Intent intent = new Intent(context, NearbyStoreActivity.class);
                context.startActivity(intent);
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context, message);
            }
        });
    }

    public void saveUserRequireInfoForCustomer(
            final Context context,
            String name,
            String idCard,
            int isMan,
            ConditionBean.SelectorData jobData,
            String city,
            String address,
            int hasBaby,
            int hasOld,
            ConditionBean.SelectorData doorData,
            ConditionBean.SelectorData styleData,
            String area,
            ConditionBean.SelectorData priceData,
            String preTime,
            int designStateId,
            int projectStateId,
            int supervisionStateId,
            int totalStateId,
            int id,
            String experienceName,
            String experiencePhone
    ) {
        Map<String, Object> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        param.put(DecorateManageView.KEY_DECORATE_NAME, name);
        param.put("idCode", idCard);
        param.put(DecorateManageView.KEY_DECORATE_GENDER, isMan);
        param.put(DecorateManageView.KEY_DECORATE_JOB_VALUE, jobData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_JOB_NAME, jobData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_CITY, city);
        param.put(DecorateManageView.KEY_DECORATE_ADDRESS, address);
        param.put(DecorateManageView.KEY_DECORATE_BABY, hasBaby);
        param.put(DecorateManageView.KEY_DECORATE_OLD, hasOld);
        param.put(DecorateManageView.KEY_DECORATE_DOOR_VALUE, doorData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_DOOR_NAME, doorData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_VALUE, styleData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_NAME, styleData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_AREA, area);
        param.put(DecorateManageView.KEY_DECORATE_PRICE_VALUE, priceData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_PRICE_NAME, priceData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_PRE_TIME, preTime);

        param.put(DecorateManageView.KEY_designStateId, designStateId);
        param.put(DecorateManageView.KEY_projectStateId, projectStateId);
        param.put(DecorateManageView.KEY_supervisionStateId, supervisionStateId);
        param.put(DecorateManageView.KEY_totalStateId, totalStateId);
//        param.put(KEY_ID,id);
        if (!TextUtils.isEmpty(experienceName)) {
            param.put(DecorateManageView.KEY_EXPERIENCENAME, experienceName);
        }
        if (!TextUtils.isEmpty(experienceName)) {
            param.put(DecorateManageView.KEY_EXPERIENCEPHONE, experiencePhone);
        }
        mView.showProgress();
        decorateModel.saveUserRequireInfoForCustomer(context, param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView == null) {
                    return;
                }
                hideProgress();

                if (response != null) {
                    if (response.getCode() == RESPONSE_CODE_SUC) {
                        Intent intent = new Intent(context, NearbyStoreActivity.class);
                        context.startActivity(intent);
                        ((Activity) context).finish();
                    } else if (response.getCode() == RESPONSE_CODE_CONTRACT) {
                        Utils.showToast(context, "身份数字证书认证失败，请确认姓名与身份证号相符，或稍后再试。");
                    } else {
                        Utils.showToast(context, response.getMessage());
                    }
                } else {
                    Utils.showToast(context, "保存失败");
                }

            }

            @Override
            public void onFailure(String message) {
                if (mView == null) {
                    return;
                }
                hideProgress();
                Utils.showToast(context, message);
            }
        });
    }

    public void indexDecorateInfoForCustomer(Context context) {

        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        mView.showProgress();
        decorateModel.indexDecorateInfoForCustomer(context, param, new CallBack<DecorateDicBean>() {
            @Override
            public void onSuccess(DecorateDicBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    onLoadListener.loadData(response.getData());
                } else if (response.getCode() == RESPONSE_CODE_TIME_OUT) {
                    ConfigValue.DATA_KEY = null;
                    SPUtils.clear(context);
                    Utils.showToast(context, "token已过期");
                    LoginActivity.logout(context);
                    return;
                }

            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
            }
        });
    }

    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }
    }

    public void updateEngnieeInfo(Context context, int statusId, int piId, int priId) {
        updateEngnieeInfo(context, statusId, piId, priId, true, null);
    }

    public void engnieeIsOfficeNextStatus(Context context, int statusId, final int piId, int priId, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("engnieeId", String.valueOf(piId));
        param.put("piId", String.valueOf(priId));
        param.put("stateId", String.valueOf(statusId));
        mView.showProgress();
        decorateModel.engnieeIsOfficeNextStatus(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {

                    if (listener != null) {
                        listener.onLoad(null);
                    } else {
                        if (bindTabListener != null) {
                            bindTabListener.reload(piId);
                        }
                    }
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });

    }

    public void updateEngnieeInfo(Context context, int statusId, int piId, int priId, boolean isZero) {
        updateEngnieeInfo(context, statusId, piId, priId, isZero, null);
    }


    public void updateEngnieeInfo(final Context context, int statusId, final int piId, final int priId, final boolean isZero, final BaseView.OnLoadListener listener) {

        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put(KEY_ID, String.valueOf(piId));
        param.put("isPass", "1");
        param.put("priId", (isZero ? "0" : String.valueOf(priId)));
        param.put("remark", "");
        mView.showProgress();
        decorateModel.updateEngnieeInfo(context, param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    if (listener != null) {
                        listener.onLoad(null);
                    } else {
                        if (bindTabListener != null) {
                            bindTabListener.reload(piId);
                        }
                    }
                } else if (response != null && response.getCode() == StaticValue.RESPONSE_CODE_FAIL) {
                    Utils.showToast(context, response.getMessage());
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });
    }


    public void initFragment(DecorateManageBean.Data data) {
        String tag = DecorateManageView.FRAGMENT_PRE + data.getPpId();
        if (ft == null) {
            ft = fragmentManager.beginTransaction();
        }


        DecorateDetailFragment innerPageFragment = new DecorateDetailFragment();
        ft.add(R.id.mainContents, innerPageFragment, tag);
        ft.addToBackStack(tag);
        ft.commitAllowingStateLoss();
        innerPageFragment.initCreateFragment(data);
    }

    private void changeFragment(DecorateManageBean.Data data) {

        ft = fragmentManager.beginTransaction();
        String tag = DecorateManageView.FRAGMENT_PRE + data.getPpId();
        if (fragmentManager.findFragmentByTag(tag) != null) {
            ft.replace(R.id.mainContents,
                    fragmentManager.findFragmentByTag(tag),
                    tag);
            ft.commit();
        } else {
            DecorateDetailFragment innerPageFragment = new DecorateDetailFragment();
            ft.replace(R.id.mainContents, innerPageFragment,
                    tag);
            ft.addToBackStack(tag);
            ft.commit();
            innerPageFragment.initCreateFragment(data);
        }
    }

    public void searchFieldList(Context context, int priId, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("busiId", String.valueOf(priId));
        param.put("busiTypeId", "supervisionCheckPic");
        mView.showProgress();
        fileModel.searchFieldList(context, param, new CallBack<FileBean>() {
            @Override
            public void onSuccess(FileBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();

                if (response != null && response.getSuperCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response.getList());
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
            }
        });
    }

    public void engnieeNeedMoney(final Context context, int piId, int type, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("piId", String.valueOf(piId));
        param.put("typeId", String.valueOf(type));
        mView.showProgress();
        decorateModel.engnieeNeedMoney(context, param, new CallBack<CheckPayBean>() {
            @Override
            public void onSuccess(CheckPayBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    listener.onLoad(response);
                } else {
                    Utils.showToast(context, "步骤有问题");
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
                Utils.showToast(context, "步骤有问题");
            }
        });
    }

    public void findIsPushStateId(Context context, int ppId, final BaseView.OnLoadListener listener) {
        Map<String, String> param = new HashMap<>();
        param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        param.put("planId", String.valueOf(ppId));
        mView.showProgress();
        decorateModel.findIsPushStateId(context, param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    if (response != null && response.getData().contains("true")) {
                        listener.onLoad(true);
                    } else {
                        listener.onLoad(false);
                    }
                } else {
                    listener.onLoad(false);
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
                listener.onLoad(false);
            }
        });
    }

    private class LoadIndexDicCallBack implements CallBack<DecorateDicBean> {

        @Override
        public void onSuccess(DecorateDicBean response, Context context, Object tag) {
            if (mView == null) return;
            hideProgress();
            if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                onLoadListener.loadData(response.getData());
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
}
